// utils/multer.js
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 创建uploads目录（如果不存在）
const uploadDir = 'uploads';
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

// 权限检查
fs.access('uploads', fs.constants.W_OK, (err) => {
    if (err) console.error('目录不可写');
  });

// 存储配置
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, uploadDir);
    },
    filename: (req, file, cb) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const ext = path.extname(file.originalname);
        cb(null, file.fieldname + '-' + uniqueSuffix + ext);
    }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (allowedTypes.includes(file.mimetype)) {
        cb(null, true);
    } else {
        cb(new Error('只允许上传图片文件（JPEG/PNG/GIF/WEBP）'), false);
    }
};

// 导出配置实例
module.exports = multer({
    storage,
    fileFilter,
    limits: {
        fileSize: 5 * 1024 * 1024, // 5MB限制
        files: 1 // 每个字段最多1个文件
    }
});